package cn.jdemo.juc.thread;

/**
 *
 * Thread.interrupt()：
 * 补充:synchronized关键字获取锁的过程中不响应中断请求，这是synchronized的局限性。
 * 如果这对程序是一个问题，应该使用显式锁，后面章节我们会介绍显式锁Lock接口，它支持以响应中断的方式获取锁。
 *
 *
 */
public class interruptDemo02 {
    public static void main(String[] args) throws InterruptedException {
        test01();
    }

    /**
     * 结果分析，synchronized获取锁的过程不响应中断请求
     *
     * 执行结果:
     * Thread-0前1679920231028
     * Thread-0后1679920232041
     * Thread-1前1679920232041
     * java.lang.InterruptedException: sleep interrupted
     * 	at java.lang.Thread.sleep(Native Method)
     * 	at cn.jdemo.juc.thread.interruptDemo02.lambda$test01$1(interruptDemo02.java:51)
     * 	at java.lang.Thread.run(Thread.java:748)
     */
    private static void test01() throws InterruptedException {
        // (1)
        Thread thread1 = new Thread(() -> {
            synchronized (interruptDemo02.class) {
                try {
                    System.out.println(Thread.currentThread().getName()+"前"+System.currentTimeMillis());
                    Thread.sleep(1000L);
                    System.out.println(Thread.currentThread().getName()+"后"+System.currentTimeMillis());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread1.start();

        // (2) 保障thread1获取锁
        Thread.sleep(100L);

        // (3)
        Thread thread2 = new Thread(() -> {
            synchronized (interruptDemo02.class) {
                try {
                    System.out.println(Thread.currentThread().getName()+"前"+System.currentTimeMillis());
                    Thread.sleep(1000L);
                    System.out.println(Thread.currentThread().getName()+"后"+System.currentTimeMillis());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread2.start();
        // (4)
        Thread.sleep(10L);
        thread2.interrupt();
    }
}
